package edu.buct.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@Configuration
public class ThreadPoolConfig {

    /**
     * 核心线程数（默认线程数）
     */
    private static final int CORE_POOL_SIZE = 2 * Runtime.getRuntime().availableProcessors() + 1;

    /**
     * 最大线程数
     */
    private static final int MAX_POOL_SIZE = 128;

    /**
     * 允许线程空闲时间（单位：默认为秒）
     */
    private static final int KEEP_ALIVE_TIME = 5;

    /**
     * 任务的等待时间
     */
    private static final int AWAIT_TERMINATION_TIME = 30;

    /**
     * 缓冲队列数
     */
    private static final int QUEUE_CAPACITY = 1200;

    /**
     * 线程池名前缀
     */
    private static final String THREAD_NAME_PREFIX = "purang-cloud-thread-pool";

    /**
     * bean的名称，默认为首字母小写的方法名
     * spring管理的线程池，顶级父类也是Executor
     */
    @Bean("executorService")// 线程池接口
    public ThreadPoolTaskExecutor executorService() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(CORE_POOL_SIZE);
        executor.setMaxPoolSize(MAX_POOL_SIZE);
        executor.setQueueCapacity(QUEUE_CAPACITY);
        executor.setKeepAliveSeconds(KEEP_ALIVE_TIME);
        executor.setThreadNamePrefix(THREAD_NAME_PREFIX);
        executor.setAwaitTerminationSeconds(AWAIT_TERMINATION_TIME);
        executor.setWaitForTasksToCompleteOnShutdown(true);

        // 线程池对拒绝任务的处理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }


}
